package com.shanzmoo.stm.admin.util;

import cn.hutool.core.util.ObjectUtil;
import com.shanzmoo.stm.admin.domain.bo.AuthStoreMemberBO;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Spring Security工具类
 *
 * @author: Gzhao 2020/11/10
 */
public class SecurityUtil {

    private SecurityUtil() {
    }


    /**
     * 获取当前登录用户用户Id
     *
     * @return 当前登录用户用户Id
     */
    public static Integer getCurrentUserId() {
        AuthStoreMemberBO currentUser = getCurrentUser();
        return ObjectUtil.isNull(currentUser) ? 0 : currentUser.getUserId();
    }

    /**
     * 获取当前登录用户用户名
     *
     * @return 当前登录用户用户名
     */
    public static String getCurrentUsername() {
        AuthStoreMemberBO currentUser = getCurrentUser();
        return ObjectUtil.isNull(currentUser) ? "匿名用户" : currentUser.getUsername();
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 当前登录用户信息，匿名登录时，为null
     */
    public static AuthStoreMemberBO getCurrentUser() {
        Object userInfo = SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        if (userInfo instanceof UserDetails) {
            return (AuthStoreMemberBO) userInfo;
        }
        return null;
    }
}
